import React, { FC, useEffect, useRef, useState } from 'react';
import { Area } from '@antv/g2plot';

let area: typeof Area | null = null;

const Library: FC = () => {
  const main = useRef<HTMLDivElement | null>(null);
  const [value, setValue] = useState<number>(0);

  useEffect(() => {
    if (!main.current) return;
    createCharts();
    return () => {
      area && area.destroy();
    };
  }, [value]);
  const createCharts: () => void = () => {
    fetch(
      'https://gw.alipayobjects.com/os/bmw-prod/b21e7336-0b3e-486c-9070-612ede49284e.json'
    )
      .then((res) => res.json())
      .then((data) => {
        area = new Area(main.current, {
          data,
          xField: 'date',
          yField: 'value',
          seriesField: 'country',
          slider: {
            start: 0.1,
            end: 0.9,
          },
          legend: {
            position: 'top-right',
          },
        });
        area.render();
      });
  };

  return (
    <>
      <button onClick={() => setValue(value + 1)}>set === {value}</button>
      {value >= 1 && <div ref={main}></div>}
    </>
  );
};

export default Library;
